
package com.hyst.seviceImpl;

import com.hyst.domain.*;
import com.hyst.repository.*;
import com.hyst.utils.DateUtils;
import com.hyst.utils.StringUtils;
import io.swagger.models.auth.In;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hyst.service.FreeAuditionService;
import com.hyst.utils.UuidTool;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Date：2018年10月09日 
 * @author： cb 
 * @version ：1.0 1.[2018年10月09日]
 */
@Service
public class FreeAuditionServiceImpl implements FreeAuditionService {

	private static final List<String> PE= Arrays.asList("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");


	@Autowired
	private FreeAuditionMapper mapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private FreeAuditionMapper freeAuditionMapper;

    @Autowired
    private RecommendMapper recommendMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private RecommendMsgMapper recommendMsgMapper;


    @Override
	public Page<FreeAudition> list(final FreeAudition freeAudition) {
		final Page<FreeAudition> page = PageHelper.startPage(freeAudition.getPageNum(), freeAudition.getPageSize());
//		mapper.select(freeAudition);
		mapper.selectNow(freeAudition); // 2018-10-13 chenbin: 删除的不再显示，只查询isdeleted=0的数据
		return page;
	}

	@Override
	public FreeAudition insert(final FreeAudition freeAudition) {
		freeAudition.setOrderId(UuidTool.randomUUID());
        mapper.insertSelective(freeAudition);
		return freeAudition;
	}

	@Override
	public FreeAudition getByPriKey(final String orderId) {
		final FreeAudition freeAudition = mapper.selecById(orderId);
		return freeAudition;
	}

	@Override
	public FreeAudition updateSelective(final FreeAudition freeAudition) {
    	try {
			if (org.apache.commons.lang3.StringUtils.isBlank(freeAudition.getTeacherId())) {
				//删除该试听记录老师的所有课程（保留+试听）
				String orderId = freeAudition.getOrderId();
				Map<String, String> sqlMap = new HashMap<>();
				sqlMap.put("teacherid", freeAudition.getTeacherId());
				sqlMap.put("studentid", freeAudition.getOrderId());
				freeAuditionMapper.deleteOrder(sqlMap);
//				if (org.apache.commons.lang3.StringUtils.isNotBlank(freeAudition.getAuditionTime())) {
//					try {
//						String date = freeAudition.getAuditionTime().split(",")[0].trim();
//						String time = freeAudition.getAuditionTime().split(",")[1].split(" ")[1].split("-")[0].trim();
//						freeAudition.setAuditionDate(date + " " + time);
//					} catch (Exception e) {
//					}
//				}
				freeAuditionMapper.updateOrder(freeAudition.getOrderId());
			}else {
				FreeAudition freeAuditiondb = freeAuditionMapper.selecById(freeAudition.getOrderId());
				if (org.apache.commons.lang3.StringUtils.isNotBlank(freeAuditiondb.getTeacherId()) && !freeAuditiondb.getTeacherId().equals(freeAudition.getTeacherId())) {
					Map<String, String> sqlMap = new HashMap<>();
					sqlMap.put("teacherid", freeAuditiondb.getTeacherId());
					sqlMap.put("studentid", freeAuditiondb.getOrderId());
					freeAuditionMapper.deleteOrder(sqlMap);
//					if (org.apache.commons.lang3.StringUtils.isNotBlank(freeAudition.getAuditionTime())) {
//						try {
//							String date = freeAudition.getAuditionTime().split(",")[0].trim();
//							String time = freeAudition.getAuditionTime().split(",")[1].split(" ")[1].split("-")[0].trim();
//							freeAudition.setAuditionDate(date + " " + time);
//						} catch (Exception e) {
//						}
//					}
					freeAuditionMapper.updateOrder(freeAudition.getOrderId());
				}
			}
			if(org.apache.commons.lang3.StringUtils.isNotBlank(freeAudition.getRecommendId()) && "请选择".equals(freeAudition.getRecommendId())){
				freeAudition.setRecommendName(null);
				freeAudition.setRecommendId(null);
			}
			mapper.updateByPrimaryKeySelective(freeAudition);
		}catch (Exception e){
    		e.printStackTrace();
		}
		return freeAudition;
	}

	@Override
	public FreeAudition update(final FreeAudition freeAudition) {
        mapper.updateByPrimaryKey(freeAudition);
		return freeAudition;
	}

	public void getPeriod(){

    }

	@Override
	public FreeAudition delete(final String orderId) {

		return null;
	}
	
	@Override
	public Page<FreeAudition> selectByCondition(final FreeAudition freeAuditionPage,String selectCondition) {
		final Page<FreeAudition> page = PageHelper.startPage(freeAuditionPage.getPageNum(), freeAuditionPage.getPageSize());
		if(selectCondition==""){
			selectCondition=null;
		}
		String []a=selectCondition.split("&");
		FreeAudition freeAudition = new FreeAudition();
		if( (!a[0].equals("all")) && (!a[1].equals("all"))){
			freeAudition.setFuzerenId(a[0]);
			freeAudition.setState(a[1]);
		}
		else{
			if(!a[0].equals("all")){
				freeAudition.setFuzerenId(a[0]);
			}
			if(!a[1].equals("all")){
				freeAudition.setState(a[1]);
			}			
		}

		switch (freeAudition.getState()) {
			case "1":
				freeAudition.setState("待跟进");
				break;
			case "2":
				freeAudition.setState("跟进中");
				break;
			case "3":
				freeAudition.setState("完成");
				break;
			case "4":
				freeAudition.setState("失联");
				break;
		}
		mapper.getListByCondition(freeAudition);
		return page;
	}
	
	@Override
	public Page<FreeAudition> searchByPhone(final FreeAudition freeAuditionPage,String phone) {
		final Page<FreeAudition> page = PageHelper.startPage(freeAuditionPage.getPageNum(), freeAuditionPage.getPageSize());
		if(phone==""){
			phone=null;
		}
		FreeAudition freeAudition = new FreeAudition();
		freeAudition.setPhone(phone);
		mapper.getListByPhone(freeAudition);
		return page;
	}
	
	@Override
	public Page<FreeAudition> searchByName(final FreeAudition freeAuditionPage,String name) {
		final Page<FreeAudition> page = PageHelper.startPage(freeAuditionPage.getPageNum(), freeAuditionPage.getPageSize());
		if(name==""){
			name=null;
		}
		FreeAudition freeAudition = new FreeAudition();
		freeAudition.setEnName(name);
		mapper.getListByName(freeAudition);
		return page;
	}
	
	// 2018-10-13 chenbin: 新增
    @Transactional
	@Override
	public FreeAudition InsertToAudition(final String orderId) {
		try {
			System.out.println(orderId);
			FreeAudition freeAudition = new FreeAudition();
			freeAudition.setOrderId(orderId);
			FreeAudition finalFreeAudition = mapper.selecById(orderId);
			FreeAudition stdFreeAudition = mapper.selecById(orderId);

			if(org.apache.commons.lang3.StringUtils.isNotBlank(stdFreeAudition.getAuditionType())){
				switch (stdFreeAudition.getAuditionType()) {
					case "新试听":
						stdFreeAudition.setAuditionType("0");
						break;
					case "二次试听":
						stdFreeAudition.setAuditionType("1");
						break;
					default:
						stdFreeAudition.setAuditionType("-1");
						break;
				}
			}
			if(org.apache.commons.lang3.StringUtils.isBlank(stdFreeAudition.getAuditionTime())){
				stdFreeAudition.setAuditionTime(null);
			}
			mapper.InsertToStudentTable(stdFreeAudition);
			finalFreeAudition.setRemark("");

			if (org.apache.commons.lang3.StringUtils.isNotBlank(finalFreeAudition.getAuditionTime())) {
				finalFreeAudition.setAuditionDate(finalFreeAudition.getAuditionTime().split(",")[0].trim());

				int count = 0;
				String counStr = finalFreeAudition.getAuditionTime().split(",")[1].trim();
				char[] c = counStr.toCharArray();
				for (int i = 0; i < c.length; i++) {
					String cstr = String.valueOf(c[i]);
					if ("-".equals(cstr)) {
						count++;
					}
				}
				finalFreeAudition.setHoursEnrolled(count);
			}

			mapper.InsertToAuditionData(finalFreeAudition);
			finalFreeAudition.setSubmitStatus("已提交");
			mapper.updateFreeAudition(finalFreeAudition);
			mapper.SetTryListenTrue(freeAudition);

			//免费试听提交 更新学生课表

            //如果有推荐人 则信息同步到推荐管理
            if(org.apache.commons.lang3.StringUtils.isNotBlank(finalFreeAudition.getRecommendId())){
                Recommend recommend = recommendMapper.selectByPrimaryKey(finalFreeAudition.getRecommendId());
                if(recommend ==null){
                    StudentView stuInfo = studentMapper.getStuInfo(finalFreeAudition.getRecommendId());
                    if(stuInfo!=null){
                        recommend= new Recommend();
                        recommend.setEnName(org.apache.commons.lang3.StringUtils.isNotBlank(stuInfo.getEnName())?stuInfo.getEnName():"");
                        recommend.setFuzeren(org.apache.commons.lang3.StringUtils.isNotBlank(stuInfo.getFuzerenName())?stuInfo.getFuzerenName():"");
                        recommend.setFuzerenId(org.apache.commons.lang3.StringUtils.isNotBlank(stuInfo.getFuzerenId())?stuInfo.getFuzerenId():"");
                        recommend.setGrantedAward("0");
                        recommend.setPhone(org.apache.commons.lang3.StringUtils.isNotBlank(stuInfo.getPhone())?stuInfo.getPhone():"");
                        recommend.setRemainedAward("0");
                        recommend.setSuccessTimes("0");
                        recommend.setTotalAward("0");
                        recommend.setStudentId(finalFreeAudition.getRecommendId());
                        recommendMapper.insertSelective(recommend);
                    }
                }else{
                    if(org.apache.commons.lang3.StringUtils.isNotBlank(recommend.getTotalAward())){
                        int count=Integer.valueOf(recommend.getTotalAward())+1;
                        recommend.setTotalAward(count+"");
                        recommendMapper.updateTotal(recommend);
                    }else {
						recommend.setTotalAward("1");
						recommendMapper.updateTotal(recommend);
					}
                }

                //被推薦人
                StudentView stuInfo = studentMapper.getStuInfo(finalFreeAudition.getOrderId());
                if(stuInfo!=null){
                    StudentView stuInfoRecommend = studentMapper.getStuInfo(finalFreeAudition.getRecommendId());

                    RecommendMsg recommendMsg = new RecommendMsg();
                    recommendMsg.setUniqueId(UuidTool.randomUUID());
                    recommendMsg.setRecommendDate(DateUtils.formatDate(stuInfo.getApplyTime()));
                    recommendMsg.setRecommenderId(finalFreeAudition.getRecommendId());
                    recommendMsg.setRecommenderName(finalFreeAudition.getRecommendName());
                    recommendMsg.setRecommenderPhone(stuInfoRecommend.getPhone());
                    recommendMsg.setRecommenderZoomId(stuInfoRecommend.getZoomId());

                    recommendMsg.setNewStudentId(stuInfo.getStudentId());
                    recommendMsg.setNewStudentName(stuInfo.getEnName());
                    recommendMsg.setNewStudentPhone(stuInfo.getPhone());
                    recommendMsg.setNewStudentZoomId(stuInfo.getZoomId());
                    recommendMsg.setFuzerenId(stuInfo.getFuzerenId());
                    recommendMsg.setFuzeren(stuInfo.getFuzerenName());

                    recommendMsgMapper.insert(recommendMsg);
                }
            }

			return freeAudition;

		} catch (Exception e){
			e.printStackTrace();
		}
		return null;

	}
	
	// 2018-10-13 chenbin: 新增
	@Override
	public FreeAudition UpdateAudition(final String orderId) {
		System.out.println(orderId);
		FreeAudition finalFreeAudition = mapper.selectByPrimaryKey(orderId);
		mapper.UpdateStudentTable(finalFreeAudition);
//		String time = finalFreeAudition.getAuditionTime();
//		// 2018-10-14 chenbin: 针对试听管理，转换时间到日期
//		if ( time != null && time.length() > 10) {
//			String date = time.substring(0, 10);
//			finalFreeAudition.setAuditionTime(date);
//		}
		mapper.UpdateAuditionData(finalFreeAudition);
		return finalFreeAudition;
	}
	
	// 2018-10-9 chenbin: 新增
	@Override
	public FreeAudition saveAllot(final String postMsg) {
		System.out.println(postMsg);
		String []a=postMsg.split("&");
		FreeAudition freeAudition = new FreeAudition();
		if (a.length == 3) {
			freeAudition.setOrderId(a[0]);
			freeAudition.setFuzerenId(a[1]);
			freeAudition.setFuzerenName(a[2]);
		}
		else {
			return null;
		}
		mapper.saveAllotData(freeAudition);
		return freeAudition;
	}
	
	
	@Override
	public FreeAudition saveRemark(final String postMsg) {
		System.out.println(postMsg);
		String []a=postMsg.split("&");
		FreeAudition freeAudition = new FreeAudition();
		if (a.length == 2) {
			freeAudition.setOrderId(a[0]);
			freeAudition.setRemark(a[1]);
//			freeAudition.setFuzerenName(a[2]);
		}
		else {
			return null;
		}
		mapper.saveRemarkData(freeAudition);
		return freeAudition;
	}
	
	@Override
	public FreeAudition saveState(final String postMsg) {
		System.out.println(postMsg);
		String []a=postMsg.split("&");
		FreeAudition freeAudition = new FreeAudition();
		if (a.length == 2) {
			freeAudition.setOrderId(a[0]);
			freeAudition.setState(a[1]);
		}
		else {
			return null;
		}
		mapper.saveStateData(freeAudition);
		return freeAudition;
	}
	
	@Override
	public FreeAudition saveDelete(final String orderId) {
		System.out.println(orderId);
		FreeAudition freeAudition = new FreeAudition();
		freeAudition.setOrderId(orderId);
		freeAudition.setIsdeleted(1);
		mapper.saveDeleteData(freeAudition);

		//释放时间
		mapper.deleteDataTime(freeAudition);
		return freeAudition;
	}
	
	
//	
//	@Override
//	public Student savestateEdit(final String studentId) {
//		System.out.println(studentId);
//		String []a=studentId.split("&");
//		StudentView student = new StudentView();
//		student.setStudentId(a[0]);
//		student.setTryListenstate(a[1]);
//		mapper.savestateEditData(student);
//		return null;
//	}
//	
//	@Override
//	public Student savedoDelete(final String studentId) {
//		System.out.println(studentId);
//		StudentView student = new StudentView();
//		student.setStudentId(studentId);
//		student.setIsdeleted(1);
//		mapper.savedoDeleteData(student);
//		return null;
//	}



}
